import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

import './Login.css';
import { API_BASE_URL_WSC } from '../utils/config';

import {
  initFaceAPI,
  getFaceDescriptor,
  recognizeFace,
  registerFace,
} from './faceDetectionWSC';
import { LivenessDetector, SpeechRecognitionHelper } from './livenessDetection';
import type { LivenessState } from './livenessDetection';

// 语音播报功能
const speak = (text: string) => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'zh-CN';
    utterance.rate = 0.8;
    utterance.pitch = 1;
    speechSynthesis.speak(utterance);
  }
};

// 播放提示音
const playNotificationSound = (type: 'success' | 'error' | 'warning') => {
  try {
    // 创建音频上下文
    const audioContext = new (window.AudioContext ||
      (window as unknown as { webkitAudioContext: typeof AudioContext })
        .webkitAudioContext)();
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    // 根据类型设置不同的音调和持续时间
    switch (type) {
      case 'success':
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(
          1000,
          audioContext.currentTime + 0.1
        );
        oscillator.frequency.setValueAtTime(
          1200,
          audioContext.currentTime + 0.2
        );
        break;
      case 'error':
        oscillator.frequency.setValueAtTime(400, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(
          300,
          audioContext.currentTime + 0.1
        );
        oscillator.frequency.setValueAtTime(
          200,
          audioContext.currentTime + 0.2
        );
        break;
      case 'warning':
        oscillator.frequency.setValueAtTime(600, audioContext.currentTime);
        oscillator.frequency.setValueAtTime(
          500,
          audioContext.currentTime + 0.1
        );
        break;
    }

    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(
      0.01,
      audioContext.currentTime + 0.3
    );

    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.3);
  } catch (error) {
    console.error('播放提示音失败:', error);
  }
};

export default function Login() {
  const navigate = useNavigate();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState<{
    username?: string;
    password?: string;
  }>({});
  const [rememberPassword, setRememberPassword] = useState(false);
  // 新增状态
  const [isRegisterMode, setIsRegisterMode] = useState(false);
  const [email, setEmail] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [registerErrors, setRegisterErrors] = useState<{
    username?: string;
    password?: string;
    email?: string;
    confirmPassword?: string;
  }>({});

  // 人脸识别相关状态
  const [isFaceMode, setIsFaceMode] = useState(false);

  // 人脸识别状态
  const [isModelLoaded, setIsModelLoaded] = useState(false);
  const [faceDetected, setFaceDetected] = useState(false);
  const [currentFaceDescriptor, setCurrentFaceDescriptor] =
    useState<Float32Array | null>(null);
  const [detectionResult, setDetectionResult] = useState<string>('');

  // 活体检测相关状态
  const [livenessState, setLivenessState] = useState<LivenessState>('idle');
  const [headShakeProgress, setHeadShakeProgress] = useState(0);
  const [mouthOpenProgress, setMouthOpenProgress] = useState(0);
  const [blinkProgress, setBlinkProgress] = useState(0);
  const [speechProgress, setSpeechProgress] = useState(0);
  const [randomDigit, setRandomDigit] = useState<string>('');
  const [recognizedSpeech, setRecognizedSpeech] = useState<string>('');
  const [headYawAngle, setHeadYawAngle] = useState<number>(0);
  const [mouthOpenRatio, setMouthOpenRatio] = useState(0);
  const [blinkCount, setBlinkCount] = useState(0);
  const [eyeAspectRatio, setEyeAspectRatio] = useState(0);

  // 引用
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const livenessDetectorRef = useRef<LivenessDetector | null>(null);
  const speechRecognitionRef = useRef<SpeechRecognitionHelper | null>(null);

  // 初始化状态跟踪
  const [isLivenessDetectorReady, setIsLivenessDetectorReady] = useState(false);

  // 表单验证
  const validateForm = () => {
    const newErrors: { username?: string; password?: string } = {};

    if (!username.trim()) {
      newErrors.username = '请输入用户名';
      speak('请输入用户名');
    }

    if (!password.trim()) {
      newErrors.password = '请输入密码';
      speak('请输入密码');
    } else if (password.length < 6) {
      newErrors.password = '密码长度至少6位';
      speak('密码长度至少6位');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 注册表单验证
  const validateRegisterForm = () => {
    const newErrors: {
      username?: string;
      password?: string;
      email?: string;
      confirmPassword?: string;
    } = {};

    if (!username.trim()) {
      newErrors.username = '请输入用户名';
      speak('请输入用户名');
    }

    if (!password.trim()) {
      newErrors.password = '请输入密码';
      speak('请输入密码');
    } else if (password.length < 6) {
      newErrors.password = '密码长度至少6位';
      speak('密码长度至少6位');
    }

    if (email && !/^\S+@\S+\.\S+$/.test(email)) {
      newErrors.email = '请输入正确的邮箱格式';
      speak('请输入正确的邮箱格式');
    }

    if (password !== confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
      speak('两次输入的密码不一致');
    }

    setRegisterErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      // 调用后端登录接口
      const response = await fetch(`${API_BASE_URL_WSC}/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: username.trim(),
          password: password,
        }),
      });

      const data = await response.json();

      if (data.success) {
        // 登录成功
        console.warn('登录成功:', data.data);

        // 保存登录信息到localStorage
        const userData = {
          _id: data.data.userId || Date.now().toString(),
          username: data.data.username,
          image:
            'https://img1.baidu.com/it/u=3217838212,795208401&fm=253&fmt=auto&app=138&f=JPEG?w=514&h=500',
          isLoggedIn: true,
        };
        localStorage.setItem('currentUser', JSON.stringify(userData));

        // 语音播报和提示音
        speak(`登录成功！欢迎回来，${data.data.username}`);
        playNotificationSound('success');

        // 显示成功消息
        alert(`登录成功！欢迎回来，${data.data.username}`);

        // 跳转到首页
        navigate('/');
      } else {
        // 登录失败
        speak('登录失败，请重试');
        playNotificationSound('error');
        alert(data.message || '登录失败，请重试');
      }
    } catch (error) {
      console.error('登录失败:', error);
      speak('网络错误，请检查网络连接');
      playNotificationSound('error');
      alert('网络错误，请检查网络连接');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理注册
  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateRegisterForm()) {
      return;
    }

    setIsLoading(true);

    try {
      // 调用后端注册接口
      const response = await fetch(`${API_BASE_URL_WSC}/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: username.trim(),
          password: password,
          email: email.trim() || undefined,
        }),
      });

      const data = await response.json();

      if (data.success) {
        // 注册成功
        speak(`注册成功！用户 ${data.data.username} 已创建，请使用新账号登录`);
        playNotificationSound('success');
        alert(`注册成功！用户 ${data.data.username} 已创建，请使用新账号登录`);

        // 清空表单
        setUsername('');
        setPassword('');
        setEmail('');
        setConfirmPassword('');

        // 切换到登录模式
        setIsRegisterMode(false);
      } else {
        // 注册失败
        speak('注册失败，请重试');
        playNotificationSound('error');
        alert(data.message || '注册失败，请重试');
      }
    } catch (error) {
      console.error('注册失败:', error);
      speak('网络错误，请检查网络连接');
      playNotificationSound('error');
      alert('网络错误，请检查网络连接');
    } finally {
      setIsLoading(false);
    }
  };

  // 输入框变化时清除对应错误
  const handleInputChange = (field: 'username' | 'password', value: string) => {
    if (field === 'username') {
      setUsername(value);
      if (errors.username) {
        setErrors(prev => ({ ...prev, username: undefined }));
      }
      if (registerErrors.username) {
        setRegisterErrors(prev => ({ ...prev, username: undefined }));
      }
    } else {
      setPassword(value);
      if (errors.password) {
        setErrors(prev => ({ ...prev, password: undefined }));
      }
      if (registerErrors.password) {
        setRegisterErrors(prev => ({ ...prev, password: undefined }));
      }
    }
  };

  // 键盘事件处理
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      if (isRegisterMode) {
        handleRegister(e);
      } else if (isFaceMode) {
        handleFaceLogin(e);
      } else {
        handleSubmit(e);
      }
    }
  };

  // 初始化 face-api.js 模型
  useEffect(() => {
    const loadModels = async () => {
      try {
        await initFaceAPI();
        setIsModelLoaded(true);
        console.warn('WSC人脸识别模型加载完成');
      } catch (error) {
        console.error('加载模型失败:', error);
      }
    };
    loadModels();
  }, []);

  // 初始化活体检测器
  useEffect(() => {
    const initLivenessDetector = () => {
      if (
        videoRef.current &&
        canvasRef.current &&
        !livenessDetectorRef.current
      ) {
        try {
          livenessDetectorRef.current = new LivenessDetector(
            videoRef.current,
            canvasRef.current
          );
          setIsLivenessDetectorReady(true);
          console.warn('活体检测器初始化成功');
        } catch (error) {
          console.error('活体检测器初始化失败:', error);
          setIsLivenessDetectorReady(false);
        }
      }
    };

    // 立即尝试初始化
    initLivenessDetector();

    // 如果还没初始化成功，延迟一小段时间再试（确保DOM完全渲染）
    if (!livenessDetectorRef.current) {
      const timer = setTimeout(() => {
        initLivenessDetector();
      }, 100);
      return () => clearTimeout(timer);
    } else {
      setIsLivenessDetectorReady(true);
    }

    return () => {
      if (livenessDetectorRef.current) {
        livenessDetectorRef.current.dispose();
        setIsLivenessDetectorReady(false);
      }
    };
  }, []);

  // 人脸识别相关函数
  const handleFaceModeToggle = () => {
    setIsFaceMode(!isFaceMode);
    setCurrentFaceDescriptor(null);
    setLivenessState('idle');
  };

  // 人脸登录
  const handleFaceLogin = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!currentFaceDescriptor) {
      alert('请先进行活体检测');
      return;
    }

    setIsLoading(true);

    try {
      // 使用真实的 face-api.js 进行人脸识别
      const recognizedName = recognizeFace(currentFaceDescriptor);

      if (recognizedName && recognizedName !== '未知') {
        // 登录成功
        localStorage.setItem('login_username', recognizedName);
        localStorage.setItem('login_type', 'face');
        localStorage.setItem(
          'currentUser',
          JSON.stringify({
            _id: data.data.userId || Date.now().toString(),
            username: data.data.username,
            image:
              'https://img1.baidu.com/it/u=3217838212,795208401&fm=253&fmt=auto&app=138&f=JPEG?w=514&h=500',
            isLoggedIn: true,
          })
        );

        speak(`人脸登录成功！欢迎回来，${recognizedName}`);
        playNotificationSound('success');
        alert(`人脸登录成功！欢迎回来，${recognizedName}`);
        navigate('/');
      } else {
        speak('人脸识别失败，请重试');
        playNotificationSound('error');
        alert('人脸识别失败，未识别到已注册的用户');
      }
    } catch (error) {
      console.error('人脸登录失败:', error);
      speak('人脸登录失败，请重试');
      playNotificationSound('error');
      alert('人脸登录失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 开始活体检测流程
  const startLivenessDetection = async () => {
    // 检查DOM元素是否存在
    if (!videoRef.current || !canvasRef.current) {
      alert('视频元素未准备就绪，请刷新页面重试');
      return;
    }

    // 如果livenessDetector还没有初始化，尝试重新初始化
    if (!livenessDetectorRef.current) {
      try {
        console.warn('重新初始化活体检测器...');
        livenessDetectorRef.current = new LivenessDetector(
          videoRef.current,
          canvasRef.current
        );
        setIsLivenessDetectorReady(true);
        console.warn('活体检测器重新初始化成功');
      } catch (error) {
        console.error('活体检测器初始化失败:', error);
        setIsLivenessDetectorReady(false);
        alert('活体检测器初始化失败，请刷新页面重试');
        return;
      }
    }

    try {
      // 获取摄像头权限
      const stream = await navigator.mediaDevices.getUserMedia({ video: {} });
      videoRef.current.srcObject = stream;

      // 等待视频加载
      await new Promise(resolve => {
        if (videoRef.current) {
          videoRef.current.onloadedmetadata = resolve;
        }
      });

      // 设置画布大小
      canvasRef.current.width = videoRef.current.videoWidth;
      canvasRef.current.height = videoRef.current.videoHeight;

      // 开始摇头检测
      setLivenessState('headshake');
      speak('请左右摇头完成活体检测');

      livenessDetectorRef.current.startHeadShakeDetection(
        (progress, yaw) => {
          setHeadShakeProgress(progress);
          setHeadYawAngle(yaw);
        },
        () => {
          // 摇头检测完成，开始张嘴检测
          setLivenessState('mouthopen');
          speak('请张嘴继续完成活体检测');
          setHeadShakeProgress(0);

          livenessDetectorRef.current?.startMouthOpenDetection(
            (progress, ratio) => {
              setMouthOpenProgress(progress);
              setMouthOpenRatio(ratio);
            },
            () => {
              // 张嘴检测完成，开始眨眼检测
              setLivenessState('blink');
              speak('请眨眼继续完成活体检测');
              setMouthOpenProgress(0);

              livenessDetectorRef.current?.startBlinkDetection(
                (progress, count, ear) => {
                  setBlinkProgress(progress);
                  setBlinkCount(count);
                  setEyeAspectRatio(ear);
                },
                () => {
                  // 眨眼检测完成，开始语音检测
                  setLivenessState('speech');
                  speak('请大声朗读屏幕上的数字');
                  setBlinkProgress(0);

                  startSpeechDetection();
                },
                () => {
                  // 眨眼检测超时
                  setLivenessState('idle');
                  speak('眨眼检测超时，请重试');
                  alert('眨眼检测超时，请重试');
                }
              );
            },
            () => {
              // 张嘴检测超时
              setLivenessState('idle');
              speak('张嘴检测超时，请重试');
              alert('张嘴检测超时，请重试');
            }
          );
        },
        () => {
          // 摇头检测超时
          setLivenessState('idle');
          speak('摇头检测超时，请重试');
          alert('摇头检测超时，请重试');
        }
      );
    } catch (error) {
      console.error('启动活体检测失败:', error);
      alert('无法访问摄像头，请确保已授予摄像头权限');
    }
  };

  // 开始语音检测
  const startSpeechDetection = () => {
    if (speechRecognitionRef.current) {
      speechRecognitionRef.current.stopListening();
    }

    speechRecognitionRef.current = new SpeechRecognitionHelper();

    // 生成随机数字
    const digits = Math.floor(Math.random() * 9000) + 1000;
    const digitString = digits.toString();
    setRandomDigit(digitString);

    speechRecognitionRef.current.startListening(
      result => {
        setRecognizedSpeech(result.transcript);
        setSpeechProgress(50);
      },
      () => {
        // 语音识别结束
        setLivenessState('completed');
        setSpeechProgress(100);
        speak('活体检测完成');

        // 提取人脸特征
        extractFaceFeatures();
      },
      error => {
        console.error('语音识别错误:', error);
        setLivenessState('idle');

        // 根据错误类型提供不同的处理
        let errorMessage = '语音识别失败，请重试';
        if (error.includes('网络连接问题')) {
          errorMessage = '网络连接不稳定，建议跳过语音验证或检查网络连接';
        } else if (error.includes('麦克风权限被拒绝')) {
          errorMessage = '麦克风权限被拒绝，请在浏览器中允许麦克风访问';
        } else if (error.includes('未检测到语音')) {
          errorMessage = '未检测到语音，请大声朗读数字后重试';
        } else if (error.includes('无法访问麦克风')) {
          errorMessage = '无法访问麦克风，请检查麦克风设备';
        } else if (error.includes('多次失败')) {
          errorMessage = '语音识别多次失败，建议跳过语音验证或刷新页面重试';
        }

        speak(errorMessage);
        alert(errorMessage);
      }
    );
  };

  // 提取人脸特征
  const extractFaceFeatures = async () => {
    if (!videoRef.current) return;

    try {
      const descriptor = await getFaceDescriptor(videoRef.current);
      if (descriptor) {
        setCurrentFaceDescriptor(descriptor);
        setFaceDetected(true);
        setDetectionResult('人脸特征提取成功');
      } else {
        setDetectionResult('未检测到人脸');
      }
    } catch (error) {
      console.error('提取人脸特征失败:', error);
      setDetectionResult('人脸特征提取失败');
    }
  };

  // 停止活体检测
  const stopLivenessDetection = () => {
    setLivenessState('idle');
    setHeadShakeProgress(0);
    setMouthOpenProgress(0);
    setBlinkProgress(0);
    setSpeechProgress(0);
    setRandomDigit('');
    setRecognizedSpeech('');

    if (livenessDetectorRef.current) {
      livenessDetectorRef.current.stop();
    }

    if (speechRecognitionRef.current) {
      speechRecognitionRef.current.stopListening();
    }

    if (videoRef.current?.srcObject) {
      const stream = videoRef.current.srcObject as MediaStream;
      stream.getTracks().forEach(track => track.stop());
      videoRef.current.srcObject = null;
    }
  };

  // 微信登录
  const handleWechatLogin = async () => {
    try {
      // 清除 baseURL（或设置为其他值）
      axios.defaults.baseURL = '';
      const response = await axios.get('/api', {
        params: {
          act: 'login',
          appid: '3521', // 自己去官网申请
          appkey: 'a010aaf9582fe1587b08b283a47ca14b', // 自己去官网申请
          type: 'wx',
          redirect_uri: 'http://127.0.0.1:5173/wx-callback', // 回调地址
        },
      });
      // 保存 code
      window.open(response.data.url, '_self'); // 打开第三方登录页面
    } catch (error) {
      console.error('微信登录错误:', error);
      speak('微信登录失败，请重试');
      playNotificationSound('error');
      alert('微信登录失败，请重试');
    }
  };

  return (
    <div className="login-container">
      <div className="login-form">
        <h2 className="login-title">
          {isRegisterMode ? '账号注册' : isFaceMode ? '人脸识别' : '账号登录'}
        </h2>

        {/* 模式切换按钮 */}
        <div className="mode-switcher">
          <button
            type="button"
            className={`mode-btn ${!isRegisterMode && !isFaceMode ? 'active' : ''}`}
            onClick={() => {
              setIsRegisterMode(false);
              setIsFaceMode(false);
              setUsername('');
              setPassword('');
              setEmail('');
              setConfirmPassword('');
              setErrors({});
              setRegisterErrors({});
            }}
          >
            密码登录
          </button>
          <button
            type="button"
            className={`mode-btn ${isFaceMode ? 'active' : ''}`}
            onClick={handleFaceModeToggle}
          >
            人脸识别
          </button>
          <button
            type="button"
            className={`mode-btn ${isRegisterMode ? 'active' : ''}`}
            onClick={() => {
              setIsRegisterMode(true);
              setIsFaceMode(false);
              setUsername('');
              setPassword('');
              setEmail('');
              setConfirmPassword('');
              setErrors({});
              setRegisterErrors({});
            }}
          >
            账号注册
          </button>
        </div>

        {isFaceMode ? (
          // 活体检测人脸识别表单
          <div className="face-form">
            {/* 摄像头显示区域 */}
            <div
              className="video-container"
              style={{
                position: 'relative',
                width: '300px',
                height: '300px',
                margin: '20px auto',
                borderRadius: '50%',
                overflow: 'hidden',
                border: '3px solid #4CAF50',
              }}
            >
              <video
                ref={videoRef}
                autoPlay
                playsInline
                muted
                style={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                  transform: 'scale(1.2)',
                }}
              />
              <canvas
                ref={canvasRef}
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                }}
              />
            </div>

            {/* 活体检测状态显示 */}
            <div className="liveness-status">
              {livenessState === 'idle' && (
                <div>
                  {/* 初始化状态指示器 */}
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                      marginBottom: '10px',
                      padding: '8px',
                      backgroundColor: isLivenessDetectorReady
                        ? '#e8f5e8'
                        : '#fff3e0',
                      borderRadius: '5px',
                      border: `1px solid ${isLivenessDetectorReady ? '#4caf50' : '#ff9800'}`,
                    }}
                  >
                    <div
                      style={{
                        width: '12px',
                        height: '12px',
                        borderRadius: '50%',
                        backgroundColor: isLivenessDetectorReady
                          ? '#4caf50'
                          : '#ff9800',
                        animation: isLivenessDetectorReady
                          ? 'none'
                          : 'pulse 2s infinite ease-in-out',
                        transition: 'all 0.3s ease',
                      }}
                    ></div>
                    <span
                      style={{
                        fontSize: '14px',
                        color: isLivenessDetectorReady ? '#2e7d32' : '#e65100',
                      }}
                    >
                      {isLivenessDetectorReady
                        ? '✅ 活体检测器已就绪'
                        : '⏳ 正在初始化活体检测器...'}
                    </span>
                  </div>

                  <h3 style={{ color: '#666', margin: '10px 0' }}>
                    请点击&quot;开始活体检测&quot;按钮
                  </h3>
                </div>
              )}

              {livenessState === 'headshake' && (
                <div>
                  <h3 style={{ color: '#2196F3', margin: '10px 0' }}>
                    请左右摇头，完成活体检测
                  </h3>
                  <div
                    className="progress-container"
                    style={{
                      width: '100%',
                      height: '20px',
                      backgroundColor: '#e0e0e0',
                      borderRadius: '10px',
                      margin: '10px 0',
                    }}
                  >
                    <div
                      className="progress-bar"
                      style={{
                        width: `${headShakeProgress}%`,
                        height: '100%',
                        backgroundColor: '#2196F3',
                        borderRadius: '10px',
                        transition: 'width 0.3s',
                      }}
                    ></div>
                  </div>
                  <div style={{ color: '#666', fontSize: '14px' }}>
                    进度: {headShakeProgress}% | 偏转角度:{' '}
                    {headYawAngle.toFixed(1)}°
                  </div>
                </div>
              )}

              {livenessState === 'mouthopen' && (
                <div>
                  <h3 style={{ color: '#2196F3', margin: '10px 0' }}>
                    请张嘴，继续完成活体检测
                  </h3>
                  <div
                    className="progress-container"
                    style={{
                      width: '100%',
                      height: '20px',
                      backgroundColor: '#e0e0e0',
                      borderRadius: '10px',
                      margin: '10px 0',
                    }}
                  >
                    <div
                      className="progress-bar"
                      style={{
                        width: `${mouthOpenProgress}%`,
                        height: '100%',
                        backgroundColor: '#2196F3',
                        borderRadius: '10px',
                        transition: 'width 0.3s',
                      }}
                    ></div>
                  </div>
                  <div style={{ color: '#666', fontSize: '14px' }}>
                    进度: {mouthOpenProgress}% | 嘴部比率:{' '}
                    {mouthOpenRatio.toFixed(3)}
                  </div>
                </div>
              )}

              {livenessState === 'blink' && (
                <div>
                  <h3 style={{ color: '#2196F3', margin: '10px 0' }}>
                    请眨眼，继续完成活体检测
                  </h3>
                  <div
                    className="progress-container"
                    style={{
                      width: '100%',
                      height: '20px',
                      backgroundColor: '#e0e0e0',
                      borderRadius: '10px',
                      margin: '10px 0',
                    }}
                  >
                    <div
                      className="progress-bar"
                      style={{
                        width: `${blinkProgress}%`,
                        height: '100%',
                        backgroundColor: '#2196F3',
                        borderRadius: '10px',
                        transition: 'width 0.3s',
                      }}
                    ></div>
                  </div>
                  <div style={{ color: '#666', fontSize: '14px' }}>
                    进度: {blinkProgress}% | 眨眼次数: {blinkCount}/5 |
                    眼睛比率: {eyeAspectRatio.toFixed(3)}
                  </div>
                </div>
              )}

              {livenessState === 'speech' && (
                <div>
                  <h3 style={{ color: '#2196F3', margin: '10px 0' }}>
                    请大声朗读:{' '}
                    <span style={{ fontWeight: 'bold', fontSize: '28px' }}>
                      {randomDigit}
                    </span>
                  </h3>
                  <div
                    style={{
                      fontSize: '12px',
                      color: '#666',
                      marginBottom: '10px',
                      padding: '5px',
                      backgroundColor: '#f0f8ff',
                      borderRadius: '3px',
                      border: '1px solid #e0e0e0',
                    }}
                  >
                    💡
                    提示：如果语音识别有问题，可以点击&quot;跳过语音识别&quot;按钮
                  </div>
                  <div
                    className="progress-container"
                    style={{
                      width: '100%',
                      height: '20px',
                      backgroundColor: '#e0e0e0',
                      borderRadius: '10px',
                      margin: '10px 0',
                    }}
                  >
                    <div
                      className="progress-bar"
                      style={{
                        width: `${speechProgress}%`,
                        height: '100%',
                        backgroundColor:
                          recognizedSpeech && recognizedSpeech !== randomDigit
                            ? '#f44336'
                            : '#2196F3',
                        borderRadius: '10px',
                        transition: 'width 0.3s',
                      }}
                    ></div>
                  </div>
                  {recognizedSpeech && (
                    <div
                      style={{
                        color:
                          recognizedSpeech !== randomDigit
                            ? '#f44336'
                            : '#2196F3',
                        marginTop: '10px',
                        fontSize: '16px',
                      }}
                    >
                      识别结果: {recognizedSpeech}
                    </div>
                  )}
                </div>
              )}

              {livenessState === 'completed' && (
                <div>
                  <h3 style={{ color: 'green', margin: '10px 0' }}>
                    活体检测完成！
                  </h3>
                  <div style={{ color: '#666', fontSize: '14px' }}>
                    {detectionResult}
                  </div>
                </div>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="face-actions">
              {livenessState === 'idle' && (
                <button
                  type="button"
                  className="liveness-btn"
                  onClick={startLivenessDetection}
                  disabled={!isModelLoaded || isLoading}
                  style={{
                    padding: '10px 20px',
                    fontSize: '16px',
                    backgroundColor: '#4CAF50',
                    color: 'white',
                    border: 'none',
                    borderRadius: '5px',
                    cursor: 'pointer',
                    margin: '10px',
                  }}
                >
                  开始活体检测
                </button>
              )}

              {livenessState !== 'idle' && livenessState !== 'completed' && (
                <div
                  style={{
                    display: 'flex',
                    gap: '10px',
                    justifyContent: 'center',
                  }}
                >
                  <button
                    type="button"
                    className="stop-btn"
                    onClick={stopLivenessDetection}
                    style={{
                      padding: '10px 20px',
                      fontSize: '16px',
                      backgroundColor: '#f44336',
                      color: 'white',
                      border: 'none',
                      borderRadius: '5px',
                      cursor: 'pointer',
                    }}
                  >
                    停止检测
                  </button>

                  {livenessState === 'speech' && (
                    <button
                      type="button"
                      className="skip-speech-btn"
                      onClick={() => {
                        // 跳过语音识别，直接完成活体检测
                        setLivenessState('completed');
                        setSpeechProgress(100);
                        speak('跳过语音识别，活体检测完成');
                        extractFaceFeatures();
                      }}
                      style={{
                        padding: '10px 20px',
                        fontSize: '16px',
                        backgroundColor: '#ff9800',
                        color: 'white',
                        border: 'none',
                        borderRadius: '5px',
                        cursor: 'pointer',
                      }}
                    >
                      跳过语音识别
                    </button>
                  )}
                </div>
              )}

              {livenessState === 'completed' && faceDetected && (
                <div className="face-buttons">
                  <div className="form-group" style={{ marginBottom: '15px' }}>
                    <input
                      type="text"
                      value={username}
                      onChange={e => setUsername(e.target.value)}
                      className="form-input"
                      placeholder="请输入用户名（注册时）"
                      disabled={isLoading}
                    />
                  </div>

                  <div className="face-buttons">
                    <button
                      type="button"
                      className="face-register-btn"
                      onClick={async () => {
                        if (!username.trim() || !currentFaceDescriptor) {
                          alert('请输入用户名');
                          return;
                        }

                        setIsLoading(true);
                        try {
                          registerFace(username.trim(), currentFaceDescriptor);
                          speak(`${username.trim()}的人脸信息录入成功`);
                          playNotificationSound('success');
                          alert(`${username.trim()}的人脸信息录入成功！`);
                          setUsername('');
                          stopLivenessDetection();
                        } catch (error) {
                          console.error('人脸注册失败:', error);
                          speak('人脸注册失败，请重试');
                          playNotificationSound('error');
                          alert('人脸注册失败，请重试');
                        } finally {
                          setIsLoading(false);
                        }
                      }}
                      disabled={!username.trim() || isLoading}
                      style={{
                        padding: '10px 20px',
                        fontSize: '16px',
                        backgroundColor: '#2196F3',
                        color: 'white',
                        border: 'none',
                        borderRadius: '5px',
                        cursor: 'pointer',
                        margin: '5px',
                      }}
                    >
                      {isLoading ? '注册中...' : '人脸注册'}
                    </button>

                    <button
                      type="button"
                      className="face-login-btn"
                      onClick={handleFaceLogin}
                      disabled={isLoading}
                      style={{
                        padding: '10px 20px',
                        fontSize: '16px',
                        backgroundColor: '#4CAF50',
                        color: 'white',
                        border: 'none',
                        borderRadius: '5px',
                        cursor: 'pointer',
                        margin: '5px',
                      }}
                    >
                      {isLoading ? '登录中...' : '人脸登录'}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        ) : isRegisterMode ? (
          // 注册表单
          <form onSubmit={handleRegister} noValidate>
            <div className="form-group">
              <label className="form-label" htmlFor="username">
                用户名
              </label>
              <input
                id="username"
                type="text"
                value={username}
                onChange={e => handleInputChange('username', e.target.value)}
                className={`form-input ${registerErrors.username ? 'error' : ''}`}
                placeholder="请输入用户名"
                disabled={isLoading}
                autoComplete="username"
              />
              {registerErrors.username && (
                <div className="error-message">{registerErrors.username}</div>
              )}
            </div>

            <div className="form-group">
              <label className="form-label" htmlFor="email">
                邮箱（可选）
              </label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                className={`form-input ${registerErrors.email ? 'error' : ''}`}
                placeholder="请输入邮箱（可选）"
                disabled={isLoading}
                autoComplete="email"
              />
              {registerErrors.email && (
                <div className="error-message">{registerErrors.email}</div>
              )}
            </div>

            <div className="form-group">
              <label className="form-label" htmlFor="password">
                密码
              </label>
              <input
                id="password"
                type="password"
                value={password}
                onChange={e => handleInputChange('password', e.target.value)}
                className={`form-input ${registerErrors.password ? 'error' : ''}`}
                placeholder="请输入密码（至少6位）"
                disabled={isLoading}
                autoComplete="new-password"
              />
              {registerErrors.password && (
                <div className="error-message">{registerErrors.password}</div>
              )}
            </div>

            <div className="form-group">
              <label className="form-label" htmlFor="confirmPassword">
                确认密码
              </label>
              <input
                id="confirmPassword"
                type="password"
                value={confirmPassword}
                onChange={e => setConfirmPassword(e.target.value)}
                className={`form-input ${registerErrors.confirmPassword ? 'error' : ''}`}
                placeholder="请再次输入密码"
                disabled={isLoading}
                autoComplete="new-password"
              />
              {registerErrors.confirmPassword && (
                <div className="error-message">
                  {registerErrors.confirmPassword}
                </div>
              )}
            </div>

            <button type="submit" className="login-button" disabled={isLoading}>
              {isLoading ? '注册中...' : '立即注册'}
            </button>
          </form>
        ) : (
          // 登录表单
          <form onSubmit={handleSubmit} noValidate>
            <div className="form-group">
              {/* 用户图标 */}
              <svg
                className="input-icon"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
                  clipRule="evenodd"
                />
              </svg>

              <input
                id="username"
                type="text"
                value={username}
                onChange={e => handleInputChange('username', e.target.value)}
                className={`form-input ${errors.username ? 'error' : ''}`}
                placeholder="请输入账号"
                disabled={isLoading}
                autoComplete="username"
              />
              {errors.username && (
                <div className="error-message">{errors.username}</div>
              )}
            </div>

            <div className="form-group">
              {/* 密码图标 */}
              <svg
                className="input-icon"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z"
                  clipRule="evenodd"
                />
              </svg>

              <input
                id="password"
                type="password"
                value={password}
                onChange={e => handleInputChange('password', e.target.value)}
                className={`form-input ${errors.password ? 'error' : ''}`}
                placeholder="请输入密码"
                disabled={isLoading}
                autoComplete="current-password"
                onKeyPress={handleKeyPress}
              />
              {errors.password && (
                <div className="error-message">{errors.password}</div>
              )}
            </div>

            {/* 忘记密码链接 */}
            <div className="forgot-password">
              <a
                href="#"
                onClick={e => {
                  e.preventDefault();
                  alert('忘记密码功能开发中...');
                }}
              >
                忘记密码?
              </a>
            </div>

            {/* 记住密码选项 */}
            <div className="remember-password">
              <input
                type="checkbox"
                id="rememberPassword"
                checked={rememberPassword}
                onChange={e => setRememberPassword(e.target.checked)}
              />
              <label htmlFor="rememberPassword">记住密码</label>
            </div>

            <button type="submit" className="login-button" disabled={isLoading}>
              {isLoading ? '登录中...' : '登录'}
            </button>
          </form>
        )}

        <div className="login-footer">
          <p className="footer-text">选择您喜欢的登录方式</p>
          <div className="social-login">
            <button
              className="social-btn wechat-btn"
              onClick={handleWechatLogin}
              title="微信登录"
            >
              <svg
                className="social-icon"
                viewBox="0 0 24 24"
                fill="currentColor"
              >
                <path d="M8.5 12.5c0-1.4 1.1-2.5 2.5-2.5s2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5-2.5-1.1-2.5-2.5z" />
                <path d="M12 2C6.5 2 2 6.5 2 12c0 1.7.4 3.3 1.1 4.7L2 22l5.3-1.1C8.7 21.6 10.3 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.7 0-3.3-.4-4.7-1.1L4 19.6l.7-3.3C4.4 15.3 4 13.7 4 12c0-4.4 3.6-8 8-8s8 3.6 8 8-3.6 8-8 8z" />
              </svg>
              <span>微信</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
